package thesis.prototype.objects;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.StringTokenizer;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;

import android.widget.Button;

//import daniel.calc.Contact;

import thesis.prototype.HelloActivity;

public class ConnectPHP {

	DefaultHttpClient httpClient = new DefaultHttpClient();
	HttpContext localContext = new BasicHttpContext();
	BufferedReader rd;
	OutputStreamWriter wr;
	URL url;
	String baseURL;
	URLConnection conn;

	HttpResponse response = null;
	HttpPost httpPost = null;

	private static ConnectPHP instance = new ConnectPHP();

	private ConnectPHP() {
		baseURL = "http://10.0.2.2/thesis/";
	}

	public static ConnectPHP getInstance() {
		if (instance == null)
			instance = new ConnectPHP();
		return instance;
	}

	// USE: Get all locations available in the database
	public ArrayList<Location> getLocations() {
		ArrayList<Location> locs = new ArrayList<Location>();
		try {
			url = new URL(baseURL + "getLocations.php");
			conn = url.openConnection();
			rd = new BufferedReader(
					new InputStreamReader(conn.getInputStream()));
			String line;
			while ((line = rd.readLine()) != null) {
				// Parse Text
				StringTokenizer st = new StringTokenizer(line, "@");
				locs.add(new Location(st.nextToken(), st.nextToken(), Double
						.parseDouble(st.nextToken()), Double.parseDouble(st
						.nextToken()), st.nextToken()));
			}
			rd.close();
			return locs;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/*
	 * Used to input the location of a user USERS: - Coordinator (organizer) -
	 * Attendee (invitee)
	 */
	public Notification putLocation(String cellNumber, Double longitude,
			Double latitude) {
		Notification notify;
		try {
			url = new URL(baseURL + "putLocations.php");
			conn = url.openConnection();

			// Prepare Connection
			conn.setDoOutput(true);
			wr = new OutputStreamWriter(conn.getOutputStream());

			// Construct the data
			String data = "number=" + URLEncoder.encode(cellNumber, "UTF-8")
					+ "&latitude="
					+ URLEncoder.encode(latitude.toString(), "UTF-8")
					+ "&longitude="
					+ URLEncoder.encode(longitude.toString(), "UTF-8");

			wr.write(data);
			wr.flush();

			notify = new Notification(true, "Location of " + cellNumber
					+ " was successfully updated.");
		} catch (Exception e) {
			notify = new Notification(false,
					"ERROR: Location was not updated. Insert to the database failed."); // FAIL
		}
		return notify;
	}

	/*
	 * USE TO GET INVITEE LOCATIONS Used only by the organizer
	 */
	public Notification getInviteeLocations() {
		Notification notify;
		ArrayList<Contact> invited = HelloActivity.arr_invited;
		ArrayList<Location> inviteeLocations = new ArrayList<Location>();
		try {
			url = new URL(baseURL + "getInviteeLocations.php");
			conn = url.openConnection();

			// Prepare Connection
			conn.setDoOutput(true);
			wr = new OutputStreamWriter(conn.getOutputStream());
			rd = new BufferedReader(
					new InputStreamReader(conn.getInputStream()));

			// do writing and pulling of data
			String data;
			for (int i = 0; i < invited.size(); i++) {
				data = "number="
						+ URLEncoder.encode(invited.get(i).getNumber() + "",
								"UTF-8");
				wr.write(data);
				wr.flush();

				String line;
				if ((line = rd.readLine()) != null) {
					StringTokenizer st = new StringTokenizer(line);
					inviteeLocations
							.add(new Location(st.nextToken(), st.nextToken(),
									Double.parseDouble(st.nextToken()), Double
											.parseDouble(st.nextToken()), st
											.nextToken()));
					// Check for current timestamp and compare with last (OR DO
					// IN PHP)
				}
			}
			wr.close();
			rd.close();

			notify = new Notification(true, "DEADS");
		} catch (Exception e) {
			notify = new Notification(false,
					"ERROR: Location was not updated. Insert to the database failed."); // FAIL
		}
		return notify;
	}
	
	/*
	 * USE TO GET INVITEE LOCATIONS Used by the map activity
	 */
	public ArrayList<Location> getInviteeMapLocations() {
		
		ArrayList<Contact> invited = HelloActivity.arr_invited;
		ArrayList<Location> inviteeLocations = new ArrayList<Location>();
		try {
			url = new URL(baseURL + "getInviteeLocations.php");
			conn = url.openConnection();

			// Prepare Connection
			conn.setDoOutput(true);
			wr = new OutputStreamWriter(conn.getOutputStream());
			rd = new BufferedReader(
					new InputStreamReader(conn.getInputStream()));

			// do writing and pulling of data
			String data;
			for (int i = 0; i < invited.size(); i++) {
				data = "number="
						+ URLEncoder.encode(invited.get(i).getNumber() + "",
								"UTF-8");
				wr.write(data);
				wr.flush();

				String line;
				if ((line = rd.readLine()) != null) {
					StringTokenizer st = new StringTokenizer(line);
					inviteeLocations
							.add(new Location(st.nextToken(), st.nextToken(),
									Double.parseDouble(st.nextToken()), Double
											.parseDouble(st.nextToken()), st
											.nextToken()));
					// Check for current timestamp and compare with last (OR DO
					// IN PHP)
				}
			}
			wr.close();
			rd.close();

			return inviteeLocations;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public ArrayList<Meeting> getMeetings(String number) {
		ArrayList<Meeting> meetings = new ArrayList<Meeting>();
		Notification notify;
		try {
			url = new URL(baseURL + "getMeetings.php");
			conn = url.openConnection();

			// Prepare Connection
			conn.setDoOutput(true);
			wr = new OutputStreamWriter(conn.getOutputStream());
			rd = new BufferedReader(
					new InputStreamReader(conn.getInputStream()));

			// do writing and pulling of data
			String data = "number=" + URLEncoder.encode(number + "", "UTF-8");
			wr.write(data);
			wr.flush();

			String line;
			while ((line = rd.readLine()) != null) {
				StringTokenizer st = new StringTokenizer(line);
				meetings.add(new Meeting(st.nextToken(), st.nextToken(), st
						.nextToken(), st.nextToken(), st.nextToken()));
				// Check for current timestamp and compare with last (OR DO
				// IN PHP)
			}
			wr.close();
			rd.close();

			notify = new Notification(true, "DEADS");
		} catch (Exception e) {
			notify = new Notification(false,
					"ERROR: Can not connect to database"); // FAIL
		}
		
		return meetings;
	}

	// SET loc_id, agenda, timedate, organizer
	public void setMeeting(String number, String agenda, String timedate,
			String loc_id) {
		Notification notify;
		String meetingID = null;
		try {
			url = new URL(baseURL + "setMeetings.php");
			conn = url.openConnection();

			// Prepare Connection
			conn.setDoOutput(true);
			wr = new OutputStreamWriter(conn.getOutputStream());

			// do writing and pulling of data
			// for timedate use this format: 2011-02-06 13:44:22
			String data = "loc_id=" + URLEncoder.encode(loc_id, "UTF-8")
					+ "&agenda=" + URLEncoder.encode(agenda, "UTF-8")
					+ "&timedate=" + URLEncoder.encode(timedate, "UTF-8")
					+ "&organizer=" + URLEncoder.encode(number, "UTF-8"); // do
																			// this!!!!!!
			wr.write(data);
			wr.flush();

			rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			meetingID = rd.readLine();
			wr.close();
			rd.close();
			notify = new Notification(true, "DEADS");
		} catch (Exception e) {
			notify = new Notification(false, "ERROR: Can not connect to database"); // FAIL
		}
		if (meetingID != null) this.setMeetingAttendees(meetingID);
	}
	
	public void setMeetingAttendees(String meetingID){
		ArrayList<Contact> invited = HelloActivity.arr_invited;
		for (int i = 0; i < invited.size(); i++) {
			Contact c = invited.get(i);
			try {
				url = new URL(baseURL + "setMeetingAttendees.php");
					conn = url.openConnection();
					conn.setDoOutput(true);
					wr = new OutputStreamWriter(conn.getOutputStream());
					String data = "user=" + URLEncoder.encode(c.getNumber(), "UTF-8")
							+ "&meetingID=" + URLEncoder.encode(meetingID, "UTF-8");
					wr.write(data);
					wr.flush();
				rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
				rd.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public void updateStatus(String number, String meeting_id, String status) {
		try {
			url = new URL(baseURL + "updateStatus.php");
			conn = url.openConnection();
			conn.setDoOutput(true);
			wr = new OutputStreamWriter(conn.getOutputStream());
			rd = new BufferedReader(
					new InputStreamReader(conn.getInputStream()));
			String data = "number=" + URLEncoder.encode(number, "UTF-8")
					+ "&meeting_id=" + URLEncoder.encode(meeting_id, "UTF-8")
					+ "&status=" + URLEncoder.encode(status, "UTF-8");
			wr.write(data);
			wr.flush();

			rd.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
